# gui/event_editor.py - Event editor component

import os
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                             QTableWidget, QTableWidgetItem, QComboBox,
                             QLabel, QSpinBox, QDoubleSpinBox, QHeaderView,
                             QDialog, QFormLayout, QDialogButtonBox, QMessageBox)
from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot


class EventEditorDialog(QDialog):
    """Dialog for editing a single event"""

    def __init__(self, event, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Edit Event")
        self.event = event.copy()  # Make a copy to avoid modifying original until confirmed

        # Set up the UI
        self._setup_ui()

    def _setup_ui(self):
        """Set up the dialog UI"""
        layout = QFormLayout()

        # Event type selector
        self.event_type = QComboBox()
        self.event_type.addItems(["stadium", "shot", "celebration"])
        self.event_type.setCurrentText(self.event.get('type', 'stadium'))
        layout.addRow("Event Type:", self.event_type)

        # Start time
        self.start_time = QDoubleSpinBox()
        self.start_time.setRange(0, 10000)  # Large range for long videos
        self.start_time.setDecimals(2)
        self.start_time.setSingleStep(0.1)
        self.start_time.setValue(self.event.get('start_time', 0))
        layout.addRow("Start Time (s):", self.start_time)

        # End time
        self.end_time = QDoubleSpinBox()
        self.end_time.setRange(0, 10000)
        self.end_time.setDecimals(2)
        self.end_time.setSingleStep(0.1)
        self.end_time.setValue(self.event.get('end_time', 0))
        layout.addRow("End Time (s):", self.end_time)

        # Confidence score
        self.confidence = QDoubleSpinBox()
        self.confidence.setRange(0, 1)
        self.confidence.setDecimals(2)
        self.confidence.setSingleStep(0.01)
        self.confidence.setValue(self.event.get('confidence', 0.5))
        layout.addRow("Confidence:", self.confidence)

        # Display video file name (non-editable)
        video_name = os.path.basename(self.event.get('video_path', 'Unknown'))
        self.video_name = QLabel(video_name)
        layout.addRow("Video:", self.video_name)

        # Button box
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addRow(button_box)

        self.setLayout(layout)

    def get_updated_event(self):
        """Get the updated event data"""
        self.event['type'] = self.event_type.currentText()
        self.event['start_time'] = self.start_time.value()
        self.event['end_time'] = self.end_time.value()
        self.event['confidence'] = self.confidence.value()
        self.event['duration'] = self.end_time.value() - self.start_time.value()

        return self.event


class EventEditor(QWidget):
    """Widget for managing detected events"""

    # Signal emitted when an event is updated
    event_updated = pyqtSignal(dict)

    def __init__(self, database):
        super().__init__()
        self.db = database
        self.events = []

        # Set up the UI
        self._setup_ui()

    def _setup_ui(self):
        """Set up the event editor UI"""
        layout = QVBoxLayout()

        # Filter controls
        filter_layout = QHBoxLayout()

        filter_layout.addWidget(QLabel("Filter:"))

        self.filter_type = QComboBox()
        self.filter_type.addItems(["All", "stadium", "shot", "celebration"])
        self.filter_type.currentTextChanged.connect(self.apply_filters)
        filter_layout.addWidget(self.filter_type)

        self.filter_confidence = QDoubleSpinBox()
        self.filter_confidence.setRange(0, 1)
        self.filter_confidence.setDecimals(2)
        self.filter_confidence.setSingleStep(0.1)
        self.filter_confidence.setValue(0)
        self.filter_confidence.valueChanged.connect(self.apply_filters)
        filter_layout.addWidget(QLabel("Min Confidence:"))
        filter_layout.addWidget(self.filter_confidence)

        filter_layout.addStretch()

        layout.addLayout(filter_layout)

        # Events table
        self.events_table = QTableWidget()
        self.events_table.setColumnCount(7)
        self.events_table.setHorizontalHeaderLabels([
            "ID", "Type", "Start", "End", "Duration", "Confidence", "Video"
        ])
        self.events_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.events_table.horizontalHeader().setSectionResizeMode(6, QHeaderView.Stretch)
        self.events_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.events_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.events_table.doubleClicked.connect(self.edit_event)
        layout.addWidget(self.events_table)

        # Action buttons
        actions_layout = QHBoxLayout()

        self.play_btn = QPushButton("Play Event")
        self.play_btn.clicked.connect(self.play_event)
        actions_layout.addWidget(self.play_btn)

        self.edit_btn = QPushButton("Edit")
        self.edit_btn.clicked.connect(self.edit_event)
        actions_layout.addWidget(self.edit_btn)

        self.delete_btn = QPushButton("Delete")
        self.delete_btn.clicked.connect(self.delete_event)
        actions_layout.addWidget(self.delete_btn)

        actions_layout.addStretch()

        layout.addLayout(actions_layout)

        self.setLayout(layout)

    def add_event(self, event):
        """Add a new event to the table"""
        self.events.append(event)
        self.apply_filters()

    def apply_filters(self):
        """Apply filters and update the events table"""
        filtered_events = self.events.copy()

        # Apply type filter
        event_type = self.filter_type.currentText()
        if event_type != "All":
            filtered_events = [e for e in filtered_events if e.get('type') == event_type]

        # Apply confidence filter
        min_confidence = self.filter_confidence.value()
        filtered_events = [e for e in filtered_events if e.get('confidence', 0) >= min_confidence]

        # Update table
        self.update_table(filtered_events)

    def update_table(self, events):
        """Update the table with the given events"""
        self.events_table.setRowCount(0)

        for event in events:
            row = self.events_table.rowCount()
            self.events_table.insertRow(row)

            # Set data
            self.events_table.setItem(row, 0, QTableWidgetItem(str(event.get('id', ''))))
            self.events_table.setItem(row, 1, QTableWidgetItem(event.get('type', '')))
            self.events_table.setItem(row, 2, QTableWidgetItem(f"{event.get('start_time', 0):.2f}"))
            self.events_table.setItem(row, 3, QTableWidgetItem(f"{event.get('end_time', 0):.2f}"))
            self.events_table.setItem(row, 4, QTableWidgetItem(f"{event.get('duration', 0):.2f}"))
            self.events_table.setItem(row, 5, QTableWidgetItem(f"{event.get('confidence', 0):.2f}"))

            video_name = os.path.basename(event.get('video_path', 'Unknown'))
            self.events_table.setItem(row, 6, QTableWidgetItem(video_name))

    # gui/event_editor.py - Event editor component (continued)

    def get_selected_event(self):
        """Get the currently selected event"""
        selected_rows = self.events_table.selectionModel().selectedRows()
        if not selected_rows:
            return None

        row = selected_rows[0].row()
        event_id = self.events_table.item(row, 0).text()

        # Find the event with the matching ID
        for event in self.events:
            if str(event.get('id', '')) == event_id:
                return event

        return None

    def play_event(self):
        """Play the selected event in the video player"""
        event = self.get_selected_event()
        if not event:
            QMessageBox.warning(self, "No Selection", "Please select an event to play.")
            return

        # Find the main window
        main_window = self.window()
        if hasattr(main_window, 'video_player'):
            # Play the segment in the video player
            main_window.video_player.play_segment(
                event.get('start_time', 0),
                event.get('end_time', 0),
                event.get('video_path', '')
            )

    def edit_event(self):
        """Open dialog to edit the selected event"""
        event = self.get_selected_event()
        if not event:
            QMessageBox.warning(self, "No Selection", "Please select an event to edit.")
            return

        # Open the edit dialog
        dialog = EventEditorDialog(event, self)
        if dialog.exec_() == QDialog.Accepted:
            # Get the updated event
            updated_event = dialog.get_updated_event()

            # Update in our events list
            for i, e in enumerate(self.events):
                if e.get('id') == updated_event.get('id'):
                    self.events[i] = updated_event
                    break

            # Update in database
            self.db.update_event(updated_event)

            # Emit signal for other components
            self.event_updated.emit(updated_event)

            # Refresh the view
            self.apply_filters()

    def delete_event(self):
        """Delete the selected event"""
        event = self.get_selected_event()
        if not event:
            QMessageBox.warning(self, "No Selection", "Please select an event to delete.")
            return

        # Confirm deletion
        confirm = QMessageBox.question(
            self, "Confirm Deletion",
            f"Are you sure you want to delete this {event.get('type')} event?",
            QMessageBox.Yes | QMessageBox.No
        )

        if confirm == QMessageBox.Yes:
            # Remove from database
            self.db.delete_event(event.get('id'))

            # Remove from our list
            self.events = [e for e in self.events if e.get('id') != event.get('id')]

            # Refresh the view
            self.apply_filters()
